import { LockOutlined } from '@ant-design/icons';
import { useRequest } from '@umijs/hooks';
import { Button, Form, Input, message } from 'antd';
import { Store } from 'rc-field-form/lib/interface';
import React, { useState } from 'react';
import cookie from 'react-cookies';
import { modifyFetch } from '../../../utils/Request';
import { url } from '../../../utils/url';
import '../style.css';
import { Link } from 'react-router-dom';
import { getSecretString, getRsaSecretString } from '../../../utils/encrypt';

interface ModifyParams {
    step: number,
    validateToken: string,
    newPassWord: string,
    newPassWord2: string
}

export default function ModifyPassword(props: { onNext: () => void; }) {

    const [form] = Form.useForm();

    const [errorText, seterrorText] = useState<string>("")

    function onFinish(value: Store) {

        const params = {
            step: 2,
            validateToken: cookie.load(cookie.load("phoneDept") + "smsTokenDept"),
            newPassWord: getRsaSecretString(value.newPassword),
            newPassWord2: getRsaSecretString(value.comfirmPassword)
        };
        // props.onNext()
        submit.run(params as ModifyParams)
    }

    const submit = useRequest(onModify, {
        manual: true,
        loadingDelay: 200
    })

    //修改请求
    async function onModify(params: ModifyParams) {
        // console.log(params)
        // console.log("参数")
        try {
            const json = await modifyFetch(url.MODIFY_PASSWORD, params)
            if (json.success) {
                props.onNext()
                cookie.remove(cookie.load("phone") + "smsToken");
                cookie.remove("phone");
            } else if (json.code === "002") {
                seterrorText("验证超时,请重新先发送验证码!")
            } else if (json.code === "004") {
                seterrorText("两次输入密码不一致")
            } else if (json.code === "005") {
                seterrorText("密码不能为弱密码!")
            } else if (json.code === "006") {
                seterrorText("修改失败，数据异常!")
            } else if (json.code === "007") {
                seterrorText("后台异常")
            } else if (json.code === "008") {
                seterrorText("验证次数过多，请重新发送验证码!")
            }else if (json.code === "009") {
                seterrorText("密码与原密码相同，请重新修改!")
            }else if (json.code === "010") {
                seterrorText("修改失败，短信验证失败!")
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }

    return (
        <Form form={form} onFinish={onFinish}>
            <Form.Item
                name="newPassword" rules={[{ required: true, message: '必须要输入新密码!' }, { pattern: /^.*(?=.{8,16})(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$%^&*?\(\)+=\[\]\{\}_<>,.;:'"-]).*$/, message: '密码必须包含数字，字母和特殊字符,至少为8位！' }]}>
                <Input.Password prefix={<LockOutlined />} placeholder="新密码" size="large" />
            </Form.Item>
            <Form.Item dependencies={['newPassword']} name="comfirmPassword" validateTrigger="onBlur" rules={[{ required: true, message: "必须要输入确认密码" }, ({ getFieldValue }) => ({
                validator(rule, value) {
                    if (!value || getFieldValue('newPassword') === value) {
                        return Promise.resolve();
                    }
                    return Promise.reject('两次密码不一致，请检查！');
                },
            })
            ]}>
                <Input.Password prefix={<LockOutlined />} placeholder="请确认密码" size="large" />
            </Form.Item>

            <Form.Item>
                <small style={{ color: "red" }}>{errorText}</small>
                <Button size="large" type="primary" htmlType="submit">修改</Button>
            </Form.Item>

            <Link to="/">返回登录</Link>
        </Form >
    )
}
